package com.whmnx.chitchat.utils;

import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.media.Ringtone;
import android.media.RingtoneManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Build;
import android.os.Handler;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.widget.Toast;


import androidx.annotation.RequiresApi;

import com.whmnx.chitchat.R;
import com.whmnx.chitchat.base.BaseActivity;
import com.whmnx.chitchat.base.BaseApplication;
import com.whmnx.chitchat.main.MainActivity;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.TimeZone;
import java.util.stream.Collectors;

/**
 * author : huang
 * date   : 2019/12/23 0023 16:17
 * version: 1.0
 */
public class UItils {

    public static Context getContext() {
        return BaseApplication.getInstance();
    }

    // 两次点击按钮之间的点击间隔不能少于1000毫秒
    private static final int MIN_CLICK_DELAY_TIME = 2000;
    private static long lastClickTime;

    public static boolean isFastClick() {
        boolean flag = false;
        long curClickTime = System.currentTimeMillis();
        if ((curClickTime - lastClickTime) >= MIN_CLICK_DELAY_TIME) {
            flag = true;
        }
        lastClickTime = curClickTime;
        return flag;
    }


    // 判断当前的线程是不是在主线程
    public static boolean isRunInMainThread() {
        return android.os.Process.myTid() == getMainThreadId();
    }


    public static long getMainThreadId() {
        return BaseApplication.getMainThreadId();
    }

     /**
     * 获取主线程的handler
     */
    public static Handler getHandler() {
        return BaseApplication.getMainThreadHandler();
    }


    public static DisplayMetrics getDeviceDensity() {
        DisplayMetrics metrics = new DisplayMetrics();
        if (null != MainActivity.mContext)
            MainActivity.mContext.getWindowManager().getDefaultDisplay().getMetrics(metrics);
        return metrics;
    }



    /**
     * 开启activity
     *
     * @param
     */
    public static void startActivity(Class target) {
        Intent intent = new Intent(getContext(), target);
        if (BaseActivity.getForegroundActivity() != null) {
            BaseActivity.getForegroundActivity().startActivity(intent);
        } else {
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            getContext().startActivity(intent);
        }
    }

    public static boolean isPhoneNumber(String phoneNumber) {
        String telRegex = "^((1[3,5,7,8][0-9])|(15[^4,\\D])|(18[0,5-9]))\\d{8}$";
        if (TextUtils.isEmpty(phoneNumber)) {
            return false;
        } else {
            return phoneNumber.matches(telRegex);
        }
    }

    /**
     * 对toast的简易封装�?线程安全，可以在非UI线程调用�?
     */
    public static void showToastSafe(final String str) {
        if (isRunInMainThread()) {
            showToast(str);
        } else {
            post(() -> showToast(str));
        }
    }

    private static void showToast(String str) {
        Toast.makeText(getContext(), str, Toast.LENGTH_SHORT).show();
    }

    /**
     * 在主线程执行runnable
     */
    public static boolean post(Runnable runnable) {
        return getHandler().post(runnable);
    }





    public static int dip2px(Context context, float dipValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dipValue * scale + 0.5f);
    }



    public static boolean isNetWorkConnected() {
            ConnectivityManager mConnectivityManager = (ConnectivityManager) UItils.getContext().getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo mNetworkInfo = mConnectivityManager.getActiveNetworkInfo();
            if (mNetworkInfo != null) {
                return mNetworkInfo.isAvailable() && mNetworkInfo.isConnected();
            }
        return false;
    }


    public static List<String> get8date() {
        List<String> dates = new ArrayList<String>();
        final Calendar c = Calendar.getInstance();
        c.setTimeZone(TimeZone.getTimeZone("GMT+8:00"));
        SimpleDateFormat sim = new SimpleDateFormat(
                "MM-dd");
        String date = sim.format(c.getTime());
        dates.add(date);
        for (int i = 0; i < 6; i++) {
            c.add(Calendar.DAY_OF_MONTH, 1);
            date = sim.format(c.getTime());
            dates.add(date);
        }
        return dates;
    }


    /**
     * 根据年月日返回星期几
     * @param  //年份
     * @param  //月份
     * @param    //天
     * @return String //返回值直接返回星期几
     */
    public static String weekByDate (String pTime)
    {
        String str="";
        SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd");
        Date d = null;

        try {
            d = (Date) fmt.parse(pTime);
        } catch (ParseException e) {
            e.printStackTrace();
        }

        Calendar cal = Calendar.getInstance();

        cal.setTime(d);
        String[] weeks = {"星期日","星期一","星期二","星期三","星期四","星期五","星期六"};
        int weekDay = cal.get(Calendar.DAY_OF_WEEK) - 1;

        if(weekDay<0){
            weekDay = 0;
        }
        return weeks[weekDay];

      /*  switch(weekDay) {
            case 1 : str="周一"; break;
            case 2 : str="周二"; break;
            case 3 : str="周三"; break;
            case 4 : str="周四"; break;
            case 5 : str="周五"; break;
            case 6 : str="周六"; break;
            case 7 : str="周日"; break;
            default: break;
        }*/
     //  return str;
    }


    /*
     * 将时间转换为时间戳
     */
    public static long stampToDate(){
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        //当前时间
        String date = df.format(new Date());
        try {
            Date time = df.parse(date);
            long timeStam = time.getTime();
            return timeStam;
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return 0;
    }

    //时间戳转时间
    public static String timeStamp2Date(String seconds) {
        if(seconds == null || seconds.isEmpty() || seconds.equals("null")){
            return "";
        }

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        return sdf.format(new Date(Long.valueOf(seconds+"000")));
    }

    public static long dateToStamp(String s){
        String ss;
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date = null;
        try {
            date = simpleDateFormat.parse(s);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        long t = date.getTime()/1000;
        return t;
    }

    public static String getTime2(Date date) {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        return dateFormat.format(date);
    }


    //判断是否安装了微信
    public static boolean isWeixinAvilible(Context context) {
        // 获取packagemanager
        final PackageManager packageManager = context.getPackageManager();
        // 获取所有已安装程序的包信息
        List<PackageInfo> pinfo = packageManager.getInstalledPackages(0);
        if (pinfo != null) {
            for (int i = 0; i < pinfo.size(); i++) {
                String pn = pinfo.get(i).packageName;
                if (pn.equals("com.tencent.mm")) {
                    return true;
                }
            }
        }
        return false;
    }


    public static List<String> delRepeat(List<String> list) {
        List<String> listNew = new ArrayList<String>();
        for (String str : list) {
            if (!listNew.contains(str)) {
                listNew.add(str);
            }
        }
        return listNew ;
    }


    /**
     * 将sp值转换为px值，保证文字大小不变
     *
     * @param spValue
     * @param
     *            （DisplayMetrics类中属性scaledDensity）
     * @return
     */
    public static int sp2px(float spValue) {
        final float fontScale = UItils.getContext().getResources().getDisplayMetrics().scaledDensity;
        return (int) (spValue * fontScale + 0.5f);
    }


    /**
     * 播放通知声音
     */
    public static void playRingTone() {
        Uri uri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
        Ringtone rt = RingtoneManager.getRingtone(UItils.getContext(), uri);
        rt.play();
    }
}
